package com.xc.ksxt.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xc.common.object.LayuiTableResponse;
import com.xc.common.object.PageInfo;
import com.xc.common.object.ResponseEntity;
import com.xc.common.tool.Helper;
import com.xc.db.tables.*;
import com.xc.ksxt.entity.*;
import com.xc.ksxt.service.*;
import com.xc.ksxt.vo.LibQuestionVO;
import com.xc.ksxt.vo.PaperVO;
import com.xc.sys.entity.SysDictEntity;
import com.xc.sys.entity.SysUserEntity;
import com.xc.sys.service.BaseCodeNumberService;
import com.xc.sys.service.SysDictService;
import com.xc.sys.service.SysUserService;
import com.xc.sys.vo.SysUserVO;
import org.apache.commons.lang3.StringUtils;
import org.jooq.*;

import org.jooq.impl.DSL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import static org.jooq.impl.DSL.*;
@RestController
@RequestMapping("/paper")
@CrossOrigin
public class PaperController {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private DSLContext dsl;
    @Autowired
    private QuestionService questionService;
    @Autowired
    private LibChoiceService libChoiceService;
    @Autowired
    private PaperService paperService;
    @Autowired
    private ChoiceService choiceService;
    @Autowired
    private ChapterService chapterService;
    @Autowired
    private PianService pianService;
    private Paper PAPERTB = Paper.PAPER.as("PAPERTB");
    private LibChoice LIBCHOICETB = LibChoice.LIB_CHOICE.as("LIBCHOICETB");
    private Chapter CHAPTER = Chapter.CHAPTER.as("CHAPTER");
    private Pian PIANTB = Pian.PIAN.as("PIANTB");
    private Question QUESTION = Question.QUESTION.as("QUESTION");
    private LibQuestion LIBQUESTIONTB = LibQuestion.LIB_QUESTION.as("LIBQUESTIONTB");
    @Autowired
    private LibQuestionService libQuestionService;
    @CrossOrigin(origins = "*", allowedHeaders = {"*"}, methods = {RequestMethod.GET})
    @RequestMapping({"/getPageList"})
    public LayuiTableResponse<PaperVO> getPageList(HttpServletRequest request) {
        LayuiTableResponse<PaperVO> ltr = new LayuiTableResponse<>();
        Condition cond = trueCondition();
        String difficulty = request.getParameter("difficulty");
        String majorId = request.getParameter("majorId");
        String grade = request.getParameter("grade");
        String gradeYear = request.getParameter("gradeYear");
        String categoryId = request.getParameter("categoryId");
        String state = request.getParameter("state");
        String name = request.getParameter("name");
        String lg = request.getParameter("lg");
        String libQuestionId = request.getParameter("libQuestionId");
        String questionId = request.getParameter("questionId");
        String major = request.getParameter("major");
        Integer limit = Integer.valueOf(request.getParameter("limit"));
        Integer page = Integer.valueOf(request.getParameter("page"));
        if (StringUtils.isNotBlank(libQuestionId)) {
        	cond = DSL.or(cond.and(exists(selectOne().from(QUESTION).where(QUESTION.PAPER_ID.eq(PAPERTB.ID))
                    .and(QUESTION.LIB_QUESTION_ID.eq(Long.valueOf(libQuestionId))))),cond.and(
                    exists(selectOne().from(LIBQUESTIONTB).where(LIBQUESTIONTB.PAPER_ID.eq(PAPERTB.ID).and(LIBQUESTIONTB.ID.eq(Long.valueOf(libQuestionId)))))
            ));
        }
        if (StringUtils.isNotBlank(questionId)) {
        	cond = cond.and(exists(selectOne().from(QUESTION).where(QUESTION.PAPER_ID.eq(PAPERTB.ID)).and(QUESTION.ID.eq(Long.valueOf(questionId)))));
        }
        if (StringUtils.isNotBlank(lg)) {
        	cond = cond.and(PAPERTB.LG.eq( Integer.valueOf(lg) ));
        }
        if (StringUtils.isNotBlank(majorId)) {
        	cond = cond.and(PAPERTB.MAJOR.eq( Long.valueOf(majorId) ));
        }
        if (StringUtils.isNotBlank(state)) {
        	cond = cond.and(PAPERTB.STATE.eq( Integer.valueOf(state) ));
        }
        if (StringUtils.isNotBlank(categoryId)) {
        	cond = cond.and(PAPERTB.CATEGORY_ID.eq( Long.valueOf(categoryId) ));
        }
        if (StringUtils.isNotBlank(grade)) {
            Long[] grades = Helper.str2longArr(grade);
        	cond = cond.and(PAPERTB.GRADE.in(grades));
        }
        if (StringUtils.isNotBlank(gradeYear)) {
            Long[] gradeYears = Helper.str2longArr(gradeYear);
        	cond = cond.and(PAPERTB.GRADE_YEAR.in(gradeYears));
        }
        if (StringUtils.isNotBlank(major)) {
        	cond = cond.and(PAPERTB.MAJOR.eq( Long.valueOf(major) ));
        }
        if (StringUtils.isNotBlank(difficulty)) {
        	cond = cond.and(PAPERTB.DIFFICULTY.eq( Integer.valueOf(difficulty) ));
        }
        if (StringUtils.isNotBlank(name)) {
        	cond = cond.and(PAPERTB.NAME.like("%"+name+"%"));
        }
        Long count = paperService.count(cond);
        ltr.setCount(count);
        PageInfo<PaperEntity> pageInfo = new PageInfo<>(limit, page);
        Result<Record> list = paperService.select(cond, pageInfo,PAPERTB.CREATE_TIME.desc());
        List<PaperVO> paperEntityList = list.into(PaperVO.class);
        for (PaperVO paperEntity : paperEntityList){
            setTxt(paperEntity);
        }
        ltr.setData(paperEntityList);
        return ltr;
    }

	private void setTxt(PaperVO paperEntity) {
		SysUserVO user = SysUserService.getFrameCaches(paperEntity.getCreateUserId());
		paperEntity.setCreateUserName(user==null?"":user.getName());
        if(paperEntity.getCategoryId()!=null){
            LibCategoryEntity cat = LibCategoryService.getFromCaches(paperEntity.getCategoryId());
            paperEntity.setCategoryName(cat==null?"":cat.getName());
        }
        if(paperEntity.getCollegeId()!=null){
            CollegeEntity cat = CollegeService.getFromCaches(paperEntity.getCollegeId());
            paperEntity.setCollegeName(cat==null?"":cat.getName());
        }
        if(paperEntity.getGradeYear()!=null){
            GradeYearEntity cat = GradeYearService.getFromCaches(paperEntity.getGradeYear());
            paperEntity.setGradeYearName(cat==null?"":cat.getName());
        }
        if(paperEntity.getMajor()!=null){
            MajorEntity cat = MajorService.getFromCaches(paperEntity.getMajor());
            paperEntity.setMajorName(cat==null?"":cat.getName());
        }

		SysDictEntity dict = SysDictService.getFromCaches("semester," + paperEntity.getSemester());
		paperEntity.setSemesterTxt(dict==null?"":dict.getName());
        dict = SysDictService.getFromCaches("question-difficulty," + paperEntity.getDifficulty());
        paperEntity.setDifficultyTxt(dict==null?"":dict.getName());
        dict = SysDictService.getFromCaches("student-type," + paperEntity.getStudentType());
        paperEntity.setStudentTypeTxt(dict==null?"":dict.getName());
        dict = SysDictService.getFromCaches("paper-lg," + paperEntity.getLg());
        paperEntity.setLgTxt(dict==null?"":dict.getName());
        dict = SysDictService.getFromCaches("data-state," + paperEntity.getState());
        paperEntity.setStateTxt(dict==null?"":dict.getName());
        dict = SysDictService.getFromCaches("test-phase," + paperEntity.getTestPhase());
        paperEntity.setTestPhaseTxt(dict==null?"":dict.getName());
        dict = SysDictService.getFromCaches("paper-type," + paperEntity.getPaperType());
        paperEntity.setPaperTypeTxt(dict==null?"":dict.getName());
        dict = SysDictService.getFromCaches("test-type," + paperEntity.getTestType());
        paperEntity.setTestTypeTxt(dict==null?"":dict.getName());
        GradeYearEntity gr = GradeYearService.getFromCaches(paperEntity.getGradeYear());
        paperEntity.setGradeYearName(gr==null?"":gr.getName());
        GradeEntity gr2 = GradeService.getFromCaches(paperEntity.getGrade());
        paperEntity.setGradeName(gr2==null?"":gr2.getName());
        if(StringUtils.isNotEmpty(paperEntity.getMajor())){
            Result<Record1<Object>> m = dsl.select(field("name")).from(table("major")).where(field("id").eq(Long.valueOf(paperEntity.getMajor()))).fetch();
            if(m.size()==1){
                paperEntity.setMajorName(m.get(0).get(0,String.class));
            }
        }
	}

    @CrossOrigin
    @RequestMapping({"/getById"})
    public PaperVO getById(Long id) {
    	Record r = paperService.getRecordById(id);
    	if(r==null) {
    		return null;
    	}
    	PaperVO vo = r.into(PaperVO.class);
        setTxt(vo);
        return vo;
    }
    
    @RequestMapping({"/save"})
    public ResponseEntity<PaperEntity> save(@RequestBody HashMap<String,String> params, HttpServletRequest request) {
    	ResponseEntity<PaperEntity> res = new ResponseEntity<>();
    	PaperEntity paperEntity = Helper.map2Bean(new PaperEntity(), params);
    	if(StringUtils.isEmpty(paperEntity.getCode())) {
    		String code = BaseCodeNumberService.genCode("paper-code", 4);
    		paperEntity.setCode(code);
    	}
    	paperService.save(paperEntity);
        return res;
    }
	//组卷，已废弃
    @Transactional
    @PostMapping({"/generate"})
    public ResponseEntity<PaperEntity> generate(@RequestBody HashMap<String,String> params) {
        SysUserEntity me = Helper.getMe(request);
    	ResponseEntity<PaperEntity> res = new ResponseEntity<>();
    	String name = params.get("name");
    	String major = params.get("major");
        Integer[] nums = new Integer[]{Integer.valueOf(params.get("num1")),Integer.valueOf(params.get("num2")),Integer.valueOf(params.get("num3")),
                Integer.valueOf(params.get("num4")),Integer.valueOf(params.get("num5"))};
        String[] names = new String[]{"单选题","多选题","判断题","简答题","论述题"};
        Integer questionNum = Integer.valueOf(params.get("questionNum"));
        int total = nums[0] + nums[1] + nums[2] + nums[3] + nums[4];
        if(total!=questionNum){
            res.setCode(1);
            res.setMsg("组卷失败，总题数不正确");
            return res;
        }
    	String difficulty = params.get("difficulty");
    	String lg = params.get("lg");
        Condition cond = LIBQUESTIONTB.CHAPTER_ID.isNotNull()
                .and(or(LIBQUESTIONTB.LAST_USE_DATE.isNull(),LIBQUESTIONTB.LAST_USE_DATE.cast(LocalDate.class)
                .le(LocalDate.now().minusYears(3)))).and(LIBQUESTIONTB.DEL_FLAG.notEqual(-1));
        if(lg!=null){
            cond = cond.and(LIBQUESTIONTB.LG.eq(Integer.valueOf(lg)));
        }
        if(difficulty!=null){
            cond = cond.and(LIBQUESTIONTB.DIFFICULTY.eq(Integer.valueOf(difficulty)));
        }
        List<LibQuestionEntity> qList = libQuestionService.select(cond);
        List<LibQuestionEntity>[] typeLists = new LinkedList[]{new LinkedList<>(),new LinkedList<>(),new LinkedList<>(),new LinkedList<>(),new LinkedList<>(),new LinkedList<>()};
        for (LibQuestionEntity libQuestionEntity : qList) {
            typeLists[libQuestionEntity.getQuestionType()-1].add(libQuestionEntity);
        }
        Map<String,Map<Integer,LinkedList<LibQuestionEntity>>> chapterMap = new HashMap<>();
        List<ChapterEntity> chapterList = chapterService.select(CHAPTER.DEL_FLAG.notEqual(-1));
        for (ChapterEntity chapterEntity : chapterList) {
            Map<Integer,LinkedList<LibQuestionEntity>> typeMap = chapterMap.get(chapterEntity.getId());
            if(typeMap==null){
                typeMap = new HashMap<>();
            }
            for(int i=0;i<5;i++){
                LinkedList<LibQuestionEntity> readyList = typeMap.get(i+1);
                if(readyList==null){
                    readyList = new LinkedList<>();
                }
                for (LibQuestionEntity libQuestionEntity : qList) {
                    if(libQuestionEntity.getChapterId().equals(chapterEntity.getId())){
                        if((i+1)==libQuestionEntity.getQuestionType()){
                            readyList.add(libQuestionEntity);
                        }
                    }
                }
                typeMap.put((i+1),readyList);
            }

            chapterMap.put(chapterEntity.getId(),typeMap);
        }
        Map<String,Map<Integer,LinkedList<LibQuestionEntity>>> pianMap = new HashMap<>();
        List<PianEntity> pianList = pianService.select(PIANTB.DEL_FLAG.notEqual(-1));
        for (PianEntity pianEntity : pianList) {
            Map<Integer,LinkedList<LibQuestionEntity>> typeMap = pianMap.get(pianEntity.getId());
            if(typeMap==null){
                typeMap = new HashMap<>();
            }
            for(int i=0;i<5;i++){
                LinkedList<LibQuestionEntity> readyList = typeMap.get(i+1);
                if(readyList==null){
                    readyList = new LinkedList<>();
                }
                for (LibQuestionEntity libQuestionEntity : qList) {
                    if(libQuestionEntity.getPianId().equals(pianEntity.getId())){
                        if((i+1)==libQuestionEntity.getQuestionType()){
                            readyList.add(libQuestionEntity);
                        }
                    }
                }
                typeMap.put((i+1),readyList);
            }

            pianMap.put(pianEntity.getId(),typeMap);
        }
    	String data = params.get("data");
        JSONArray arr = JSON.parseArray(data);
        Integer[] chapterNums1 = new Integer[]{0,0,0,0,0},chapterNums2 = new Integer[]{0,0,0,0,0};
        List<Integer[]> numList = new ArrayList<>();
        numList.add(chapterNums1);
        numList.add(chapterNums2);
        Set<LibQuestionEntity> resutSet = new HashSet<>();
        //第二级
        for (Object o : arr) {
            JSONObject obj = (JSONObject)o;
            String dataIndex = obj.getString("dataIndex");
            String[] ss = dataIndex.split("-");
            if(ss.length==2){
                Integer chapterId = obj.getInteger("chapterId");
                Map<Integer, LinkedList<LibQuestionEntity>> xxMap = chapterMap.get(chapterId+"");
                for(int i=0;i<5;i++){
                    List<LibQuestionEntity> rlist1 = xxMap.get(i+1);//章节、题型过滤的结果
                    Integer rnum1 = obj.getInteger("num"+(i+1));
                    if(rnum1!=null){
                        if(rnum1>rlist1.size()){
                            res.setCode(1);
                            res.setMsg("组卷失败，" + "题库中"+names[i]+"数量不够");
                            return res;
                        }
                        Set<LibQuestionEntity> rset1 = new HashSet<>();
                        while (rset1.size()<rnum1){
                            int n = (int)Math.random() * rlist1.size();
                            LibQuestionEntity selected = rlist1.remove(n);
                            rset1.add(selected);
                            typeLists[i].remove(selected);
                        }
                        resutSet.addAll(rset1);
                    }
                }
            }
        }
        //第一级
        for (Object o : arr) {
            JSONObject obj = (JSONObject)o;
            String dataIndex = obj.getString("dataIndex");
            String[] ss = dataIndex.split("-");
            if(ss.length==1){
                for(int i=0;i<5;i++){
                    Integer rnum1 = obj.getInteger("num"+(i+1));
                    if(rnum1!=null){
                        List<String> reservedChapterIds = new ArrayList();
                        String pianId = obj.getString("chapterId");
                        List<LibQuestionEntity> joinedList = new ArrayList<>();
                        for (Object o2 : arr) {
                            JSONObject obj2 = (JSONObject)o2;
                            String dataIndex2 = obj2.getString("dataIndex");
                            String[] ss2 = dataIndex2.split("-");
                            if(dataIndex2.contains(dataIndex + "-")){
                                if(obj2.getInteger("num"+(i+1))!=null&&ss2.length==2){
                                    rnum1 -= obj2.getInteger("num"+(i+1));
                                }else{
                                    reservedChapterIds.add(obj2.getString("chapterId"));//章没有指定数量的
                                }
                            }
                            for (String cid : reservedChapterIds) {
                                Map<Integer, LinkedList<LibQuestionEntity>> xxMap = chapterMap.get(cid);
                                if(xxMap.get(i+1)!=null){
                                    joinedList.addAll(xxMap.get(i+1));
                                }
                            }
                        }
                        if(rnum1<0){
                            res.setCode(1);
                            res.setMsg("组卷失败，" + "篇章的"+names[i]+"数量不匹配。");
                            return res;
                        }
                        Set<LibQuestionEntity> rset1 = new HashSet<>();
                        while (rset1.size()<rnum1){
                            int n = (int)(Math.random() * joinedList.size());
                            LibQuestionEntity selected = joinedList.remove(n);
                            rset1.add(selected);
                            typeLists[i].remove(selected);
                        }
                        resutSet.addAll(rset1);
                    }
                }
            }
        }
        int successNums[] = new int[5];
        for (LibQuestionEntity libQuestionEntity : resutSet) {
            successNums[libQuestionEntity.getQuestionType()-1]++;
        }

        for (int i=0;i<5;i++){
            if(nums[i]>successNums[i]){
                Set<LibQuestionEntity> set = new HashSet<>();
                int n = 0;
                for (LibQuestionEntity libQuestionEntity : typeLists[i]) {
                    set.add(libQuestionEntity);
                    if(set.size()>=(nums[i]-successNums[i])){
                        resutSet.addAll(set);
                        break;
                    }
                }
            }
        }
        PaperEntity paperEntity = new PaperEntity();
        paperEntity.setDifficulty(difficulty==null?null:Integer.valueOf(difficulty));
        paperEntity.setLg(lg==null?null:Integer.valueOf(lg));
        paperEntity.setName(name);
        paperEntity.setCreateTime(LocalDateTime.now());
        paperEntity.setCreateUserId(me.getId());
        paperEntity.setQuestionNum(questionNum);
        paperEntity.setMajor(major);
//        paperEntity.setSubject(subject);
//        paperEntity.setGrade(Integer.valueOf(grade));
        paperEntity.setNum1(nums[0]);
        paperEntity.setNum2(nums[1]);
        paperEntity.setNum3(nums[2]);
        paperEntity.setNum4(nums[3]);
        paperEntity.setNum5(nums[4]);
        String code = BaseCodeNumberService.genCode("paper-code", 4);
        paperEntity.setCode(code);
        paperService.insert(paperEntity);
        for (LibQuestionEntity lqe : resutSet) {
            genQuestion(lqe, me, paperEntity);
        }
    	return res;
    }
    @Transactional
    @PostMapping({"/generate2"})
    public ResponseEntity<PaperEntity> generate2(@RequestBody HashMap<String,String> params) {
        SysUserEntity me = Helper.getMe(request);
    	ResponseEntity<PaperEntity> res = new ResponseEntity<>();
        res.setCode(1);
    	String joinid = params.get("joinid");
    	String grade = params.get("grade");
    	String lg = params.get("lg");
    	String gradeYear = params.get("gradeYear");
    	String semester = params.get("semester");
    	String collegeId = params.get("collegeId");
    	String categoryId = params.get("categoryId");
    	String testType = params.get("testType");
    	String paperType = params.get("paperType");
    	String major = params.get("major");
        String studentType = params.get("studentType");
    	String testPhase = params.get("testPhase");
    	String howlong = params.get("howlong");
    	String score1 = params.get("score1");
    	String score2 = params.get("score2");
    	String score3 = params.get("score3");
    	String score4 = params.get("score4");
    	String score5 = params.get("score5");
        if(StringUtils.isEmpty(collegeId)){
            res.setMsg("学院/系不能为空");
            return res;
        }
        if(StringUtils.isEmpty(major)){
            res.setMsg("考试专业不能为空");
            return res;
        }
        if(StringUtils.isEmpty(categoryId)){
            res.setMsg("考试科目不能为空");
            return res;
        }
        if(StringUtils.isEmpty(studentType)){
            res.setMsg("学生类型不能为空");
            return res;
        }

        if(StringUtils.isEmpty(gradeYear)){
            res.setMsg("考试学年不能为空");
            return res;
        }
        if(StringUtils.isEmpty(semester)){
            res.setMsg("考试学期不能为空");
            return res;
        }
        if(StringUtils.isEmpty(testPhase)){
            res.setMsg("考试阶段不能为空");
            return res;
        }
        if(StringUtils.isEmpty(paperType)){
            res.setMsg("A/B/C卷不能为空");
            return res;
        }
        if(StringUtils.isEmpty(testType)){
            res.setMsg("考试方式不能为空");
            return res;
        }

        if(StringUtils.isEmpty(lg)){
            res.setMsg("中/英文不能为空");
            return res;
        }
        if(StringUtils.isEmpty(howlong)){
            res.setMsg("考试时长不能为空");
            return res;
        }
        res.setCode(0);
        List<LibQuestionVO> qList = LibQuestionService.JOINCACHE.getIfPresent(joinid);
        List<LibQuestionEntity>[] typeLists = new LinkedList[]{new LinkedList<>(),new LinkedList<>(),new LinkedList<>(),new LinkedList<>(),new LinkedList<>(),new LinkedList<>()};
        for (LibQuestionEntity libQuestionEntity : qList) {
            typeLists[libQuestionEntity.getQuestionType()-1].add(libQuestionEntity);
        }
        PaperEntity paperEntity = paperService.getEntityById(Long.valueOf(joinid));
        SysDictEntity dict = SysDictService.getFromCaches("student-type,"+studentType);
        SysDictEntity dict2 = SysDictService.getFromCaches("test-phase,"+testPhase);
        String name = "中山大学" + dict.getName() + dict2.getName() + "考试";
        paperEntity.setName(name);
        paperEntity.setMajor(major);
        paperEntity.setTestPhase(testPhase==null?null:Integer.valueOf(testPhase));
        paperEntity.setPaperType(paperType==null?null:Integer.valueOf(paperType));
        paperEntity.setStudentType(studentType==null?null:Integer.valueOf(studentType));
        paperEntity.setCreateTime(LocalDateTime.now());
        paperEntity.setCreateUserId(me.getId());
        paperEntity.setCategoryId(categoryId);
        paperEntity.setLg(lg==null?null:Integer.valueOf(lg));
        paperEntity.setCollegeId(collegeId);
        paperEntity.setScore1(StringUtils.isEmpty(score1)?null:new BigDecimal(score1));
        paperEntity.setScore2(StringUtils.isEmpty(score2)?null:new BigDecimal(score2));
        paperEntity.setScore3(StringUtils.isEmpty(score3)?null:new BigDecimal(score3));
        paperEntity.setScore4(StringUtils.isEmpty(score4)?null:new BigDecimal(score4));
        paperEntity.setScore5(StringUtils.isEmpty(score5)?null:new BigDecimal(score5));
        if(howlong!=null&&!howlong.isEmpty()){
            paperEntity.setHowlong(Integer.valueOf(howlong));
        }
        paperEntity.setGrade(grade);
        paperEntity.setGradeYear(gradeYear);
        if(semester!=null&&!semester.isEmpty()){
            paperEntity.setSemester(Integer.valueOf(semester));
        }
        if(testType!=null&&!testType.isEmpty()){
            paperEntity.setTestType(Integer.valueOf(testType));
        }
        String code = BaseCodeNumberService.genCode("paper-code", 4);
        paperEntity.setCode(code);

        Integer[] qtnums = new Integer[]{0,0,0,0,0};
        for (LibQuestionEntity lqe : qList) {
            qtnums[lqe.getQuestionType()-1]++;
            genQuestion(lqe, me, paperEntity);
        }
        paperEntity.setNum1(qtnums[0]);
        paperEntity.setNum2(qtnums[1]);
        paperEntity.setNum3(qtnums[2]);
        paperEntity.setNum4(qtnums[3]);
        paperEntity.setNum5(qtnums[4]);
        paperService.save(paperEntity);
        res.setMsg("组卷成功");
    	return res;
    }

    private void genQuestion(LibQuestionEntity lqe, SysUserEntity me, PaperEntity paperEntity) {

        QuestionEntity qe = new QuestionEntity();
        qe.setLg(lqe.getLg());
        qe.setDifficulty(lqe.getDifficulty());
        qe.setLibId(lqe.getLibId());
        qe.setOrderno(lqe.getOrderno());
        qe.setAnalysis(lqe.getAnalysis());
        qe.setCategoryId(lqe.getCategoryId());
        qe.setPianId(lqe.getPianId());
        qe.setJieId(lqe.getJieId());
        qe.setChapterId(lqe.getChapterId());
        qe.setContentType(lqe.getContentType());
        qe.setSource(lqe.getSource());
        qe.setCreateTime(LocalDateTime.now());
        qe.setText(lqe.getText());
        qe.setAnswerText(lqe.getAnswerText());
        qe.setQuestionType(lqe.getQuestionType());
        qe.setCreateUserId(me.getId());
        qe.setLibQuestionId(lqe.getId());
        qe.setPaperId(paperEntity.getId());
        questionService.insert(qe);
        List<LibChoiceEntity> choiceList = libChoiceService.select(LIBCHOICETB.LIB_QUESTION_ID.eq(Long.valueOf(lqe.getId())).and(LIBCHOICETB.DEL_FLAG.eq(1)));
        for (LibChoiceEntity lce : choiceList) {
            ChoiceEntity ce = new ChoiceEntity();
            ce.setText(lce.getText());
            ce.setLibId(lce.getLibId());
            ce.setLibChoiceId(lce.getId());
            ce.setLibQuestionId(lqe.getId());
            ce.setCreateTime(LocalDateTime.now());
            ce.setRight(lce.getRight());
            ce.setAnswerText(lce.getAnswerText());
            ce.setIndexLetter(lce.getIndexLetter());
            ce.setQuestionId(qe.getId());
            ce.setPaperId(paperEntity.getId());
            choiceService.insert(ce);
        }
        lqe.setLastUseDate(LocalDate.now());
        libQuestionService.update(lqe);
    }

    @RequestMapping({"/delete"})
    public LayuiTableResponse<PaperEntity> delete(@RequestParam("ids[]") Long[] ids) {
        LayuiTableResponse<PaperEntity> ltr = new LayuiTableResponse<>();
        for (Long id : ids) {
            PaperEntity paper = paperService.getEntityById(id);
            if(paper.getState()==1){
                paperService.deleteById(id);
                dsl.delete(table("question")).where(field("paper_id").eq(id)).execute();
                dsl.delete(table("choice")).where(field("paper_id").eq(id)).execute();
            }
        }
        return ltr;
    }
    @RequestMapping({"/confirm"})
    @Transactional
    public LayuiTableResponse<PaperEntity> confirm(@RequestBody HashMap<String,String> params) {
        LayuiTableResponse<PaperEntity> ltr = new LayuiTableResponse<>();
        String ids = params.get("ids");
        Long[] arr = Helper.str2longArr(ids);
        for (Long id : arr) {
            PaperEntity paper = paperService.getEntityById(id);
            paper.setState(2);
            paperService.update(paper);
        }
        ltr.setCode(0);
        ltr.setMsg("状态修改成功");
        return ltr;
    }
}
